<?php
/**
 * Created by PhpStorm.
 * User: mr2longly <mr2longly@gmail.com>
 * Date: 7/9/16
 * Time: 00:19
 */

namespace Home\Model;


use Common\Library\BusinessException;
use Common\Library\Constant;

use Think\Cache\Driver\Redis;
use Think\Log;
use Think\Model;

class JPushModel {

    const MSG_TYPE_INSTALL_ORDER_PASS       = 1;      //分期订单审核通过
    const MSG_TYPE_CASH_ORDER_PASS          = 2;      //现金贷订单审核通过
    const MSG_TYPE_GET_LOG                  = 3;      //获取日志
    const MSG_TYPE_INSTALL_ORDER_WAITING    = 5;      //分期订单待审核
    const MSG_TYPE_REPAY_OVER               = 6;      //还款

    protected function jpush_http_post($url, $data)
    {
        $header[] = "Content-type:application/json";
        //$header[] = "Authorization: Basic ".base64_encode("3bc98c28e1b0ba7652405aca:11473146719cb7718584afce");//正式服务器
          $header[] = "Authorization: Basic ".base64_encode("ccbfd9f014d5eba11825dbc3:c2b301c14c7ec1807f0f5f87");//正式服务器
        //$header[] = "Authorization: Basic ".base64_encode("xxxxxxxx:xxxxxxxxxxxxx");//测试服務器
        $ch=curl_init($url);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $response = curl_exec($ch);

        if(curl_errno($ch))
        {
            print curl_error($ch);
        }
        curl_close($ch);

        Log::write("发送push：".json_encode($response, JSON_UNESCAPED_UNICODE), Log::INFO);

        return $response;
    }

    protected function jpush($msg)
    {
        $data =$msg;
        $url = 'https://api.jpush.cn/v3/push';
        $a=$this->jpush_http_post($url,$data);
        return $a;
    }

    public function send_push($data, $msgType, $push_id, $msgContent){
        $res = array(
            'platform'=>'all',
            'audience'=>array(
                'registration_id'=>array($push_id),
            ),
            'notification'=>array(
                'alert'=>'',
                'android'=>array(
                    'alert'=>$msgContent,
                    'title'=>'找钱花客户端',
                    'builder_id'=>3,
                    'extras'=>array(
                        'msg_type'=>$msgType,
                        'msg_content'=> $data
                    ),
                ),
            ),
        );
        Log::write("发送push：".json_encode($res, JSON_UNESCAPED_UNICODE), Log::INFO);
        $result = $this->jpush(json_encode($res));
        Log::write("发送push完毕：".json_encode($result, JSON_UNESCAPED_UNICODE), Log::INFO);
        return $result;
    }

}
